import 'dart:io';
import 'dart:math';

// import 'remote_page_21.dart';

import 'package:blocks_blkk/components/function_button.dart';
import 'package:blocks_blkk/components/loading_dialog.dart';
import 'package:blocks_blkk/page/app_intl.dart';
import 'package:blocks_blkk/page/device_data_context.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

import '../app_configure.dart';
// import '../pages/device_data_context.dart';
import 'package:flutter/material.dart';
// import 'package:flutter_screenutil/screenutil.dart';
// import '../general/comunication/bluetooth_mk.dart';
// import 'component/function_button.dart';
// import 'component/loading_dialog.dart';
import 'entity/devcie_entity.dart';
import 'entity/function_enum.dart';
// import 'path_page.dart';
// import 'gravity_page.dart';
// import 'remote_page_20.dart';
// import 'remote_page_30.dart';
// import 'remote_page_40.dart';
// import 'voice_page.dart';
import 'package:yundongjia_ble/yundongjia_ble.dart';

typedef MeterChange = int Function();

/*
 * 控制界基础类
 */
abstract class FunctionPage extends StatefulWidget {
  FunctionPage({super.key});

  @override
  FunctionPageState createState() => FunctionPageState();
}

class FunctionPageState extends State<FunctionPage> {
  FunctionPageState({
    this.functionType = FunctionType.Remote,
  }) {
    // this.bluetoothDanbao = BluetoothMouldking();
  }

  // BluetoothMouldking bluetoothDanbao;
  FunctionType functionType;
  double _meterAngle = -pi * 3 / 4;
  bool _accelator = false;

  //ConvertMeter _convertMeter;

  bool needConvertMeter() {
    return false;
  }

  // @override
  // void initState() {
  //   YundongjiaBle.instance.start();
  //   super.initState();
  // }

  // @override
  // void initState() {

  //   super.initState();
  // }

  @override
  void dispose() {
    setBoth(speed: 0, direction: 0);

    //YundongjiaBle.instance.stop();
    super.dispose();
  }

  //背景
  Widget background(List<Widget> children, {bool useBackground = true}) {
    // if (useBackground) {
    //   children.insert(0, _backgroundMask());
    // }
    children.insert(0, _backgroundGeneralMask());

    return Stack(
      children: children,
    );
  }

  Widget _backgroundGeneralMask() {
    return Positioned(
      top: 0,
      bottom: 0,
      left: 0,
      right: 0,
      child: Image.asset(
        'assets/background.png',
        fit: BoxFit.fill,
      ),
    );
  }

  // Widget _backgroundMask() {
  //   return Positioned(
  //     top: 0,
  //     bottom: 0,
  //     left: 0,
  //     right: 0,
  //     child: Column(
  //       children: [
  //         Expanded(child: Container()),
  //         Image.asset('assets/background_mask.png'),
  //       ],
  //     ),
  //   );
  // }

  Widget shedowBtn({GestureTapCallback? ontap, String? image}) {
    return GestureDetector(
      onTap: ontap,
      child: Container(
        margin: EdgeInsets.all(ScreenUtil().setWidth(20)),
        decoration: BoxDecoration(
          image: image != null
              ? DecorationImage(
                  image: AssetImage(image),
                )
              : null,
          shape: BoxShape.circle,
          boxShadow: const [
            BoxShadow(
                color: Colors.black,
                offset: Offset(2.0, 2.0),
                blurRadius: 2.0,
                spreadRadius: 1.0),
          ],
        ),
      ),
    );
  }

  //返回按钮
  Widget returnBtn() {
    return Positioned(
      left: ScreenUtil().setWidth(80.0),
      top: ScreenUtil().setWidth(40.0),
      width: ScreenUtil().setWidth(100),
      height: ScreenUtil().setWidth(100),
      child: shedowBtn(
          ontap: () {
            Navigator.of(context).pop();
          },
          image: 'assets/btn_return.png'),
    );
  }

  //蓝牙按钮点击事件
  void _onBluetoothBtnTap() {
    setState(() {
      if (AppConfig.instance.bluetoothStatus == 1) {
        AppConfig.instance.bluetoothStatus = 0;
      } else {
        AppConfig.instance.bluetoothStatus = 1;
      }
    });
    if (AppConfig.instance.bluetoothStatus == 1) {
      String message = AppIntl.getString('bluetoot_connect');
      Navigator.push(context, DialogRouter(LoadingDialog(message)));
      List<int> data = DeviceDataContext.instance.devcie.getPair();
      YundongjiaBle.instance.sendAdvertiseCommand(data);
      Future.delayed(const Duration(seconds: 3), () {
        List<int> stopdata = DeviceDataContext.instance.devcie.getStopPair();
        YundongjiaBle.instance.sendAdvertiseCommand(stopdata);
        Navigator.pop(context);
      });
      YundongjiaBle.instance.start();
    } else {
      YundongjiaBle.instance.stop();
    }
  }

  //加速按钮按下
  void _onAccelerateBtn() {
    setState(() {
      _accelator = !_accelator;
      setData(6, 0xF0);
      setData(5, 0xF0);
    });
  }

  //蓝牙图片
  String get _bluetoothImg {
    return AppConfig.instance.bluetoothStatus == 0
        ? 'assets/bluetooth_off.png'
        : 'assets/bluetooth_on.png';
  }

  // Color get _bluetoothShdow {
  //   return AppConfig.instance.bluetoothStatus == 0 ? null : Colors.transparent;
  // }

  //蓝牙按钮
  Widget bluetootnBtn(
      {BoxShape shape = BoxShape.circle,
      Color background = Colors.transparent,
      String image = 'assets/bluetooth_off.png'}) {
    double left = 150, top = 44, width = 60, height = 60;
    if (Platform.isIOS) {
      double screenHeight = MediaQuery.of(context).size.height;
      double screenWidth = MediaQuery.of(context).size.width;
      double w = max<double>(screenHeight, screenWidth);
      if (w > 1000) {
        left = 80;
        top = 10;
      }
    }

    return Positioned(
      left: ScreenUtil().setHeight(left),
      top: ScreenUtil().setHeight(top),
      width: ScreenUtil().setHeight(width),
      height: ScreenUtil().setHeight(height),
      child: FunctionBtn(
        image: image,
        onTap: _onBluetoothBtnTap,
        shape: shape,
        shadowColor: Colors.transparent,
        backgroundColor: background,
      ),
    );
  }

  //遥控器锁图片
  String getLockImg() {
    return '';
  }

  Color getLockShdow() {
    return Colors.transparent;
  }

  void onLockBtn() {}

  //遥控器锁
  Widget lockBtn() {
    return Positioned(
      left: ScreenUtil().setWidth(280.0),
      top: ScreenUtil().setWidth(40.0),
      width: ScreenUtil().setWidth(80),
      height: ScreenUtil().setWidth(80),
      child: FunctionBtn(
        image: getLockImg(),
        onTap: onLockBtn,
        shape: BoxShape.circle,
        shadowColor: getLockShdow(),
      ),
    );
  }

  //遥控按钮
  Widget remoteBtn({bool pressed = false}) {
    return channelBtn(
      right: ScreenUtil().setHeight(340.0),
      top: ScreenUtil().setHeight(50.0),
      width: ScreenUtil().setHeight(80.0),
      height: ScreenUtil().setHeight(80.0),
      imagename:
          (pressed ? 'assets/mode_remote_on.png' : 'assets/mode_remote.png'),
      ontap: pressed ? null : remoteBtnOntap,
    );
  }

  //陀螺仪按钮
  Widget gsensorBtn({bool pressed = false}) {
    return channelBtn(
      right: ScreenUtil().setHeight(240.0),
      top: ScreenUtil().setHeight(50.0),
      width: ScreenUtil().setHeight(80.0),
      height: ScreenUtil().setHeight(80.0),
      imagename:
          (pressed ? 'assets/mode_gsensor_on.png' : 'assets/mode_gsensor.png'),
      ontap: pressed ? null : gravityBtnOntap,
    );
  }

  //路径按钮
  Widget pathBtn({bool pressed = false}) {
    return channelBtn(
      right: ScreenUtil().setHeight(140.0),
      top: ScreenUtil().setHeight(50.0),
      width: ScreenUtil().setHeight(80.0),
      height: ScreenUtil().setHeight(80.0),
      imagename: (pressed ? 'assets/mode_path_on.png' : 'assets/mode_path.png'),
      ontap: pressed ? null : pathBtnOntap,
    );
  }

  //语音按钮
  Widget voiceBtn({bool pressed = false}) {
    return channelBtn(
      right: ScreenUtil().setHeight(40.0),
      top: ScreenUtil().setHeight(50.0),
      width: ScreenUtil().setHeight(80.0),
      height: ScreenUtil().setHeight(80.0),
      imagename:
          (pressed ? 'assets/mode_voice_on.png' : 'assets/mode_voice.png'),
      ontap: pressed ? null : voiceBtnOntap,
    );
  }

  String get accelerateImg =>
      _accelator ? 'assets/icon_speed_p.png' : 'assets/icon_speed.png';

  //加速按钮
  Widget accelerateBtn() {
    return Positioned(
      right: ScreenUtil().setWidth(380.0),
      bottom: ScreenUtil().setHeight(60.0),
      width: ScreenUtil().setWidth(76.0),
      height: ScreenUtil().setWidth(76),
      child: FunctionBtn(
        image: accelerateImg,
        onTap: _onAccelerateBtn,
        shape: BoxShape.circle,
      ),
    );
  }

  //替换按钮
  Widget switchBtn(String image) {
    return Positioned(
      right: ScreenUtil().setWidth(60.0),
      bottom: ScreenUtil().setHeight(60.0),
      width: ScreenUtil().setWidth(76.0),
      height: ScreenUtil().setWidth(76),
      child: FunctionBtn(
        image: image,
        onTap: onSwitchTap,
      ),
    );
  }

  //设置按钮
  Widget settingBtn() {
    return Positioned(
      left: ScreenUtil().setWidth(60.0),
      bottom: ScreenUtil().setHeight(60.0),
      width: ScreenUtil().setWidth(76.0),
      height: ScreenUtil().setWidth(76),
      child: FunctionBtn(
        image: 'assets/control_help_icon.png',
        onTap: onSettingTap,
      ),
    );
  }

  //仪表盘背景
  BoxDecoration _techMeterBackground() {
    return const BoxDecoration(
      image: DecorationImage(
        image: AssetImage('assets/meter_bg.png'),
      ),
      boxShadow: [
        BoxShadow(
          color: Colors.grey,
          blurRadius: 20,
          spreadRadius: 0.5,
        ),
      ],
      shape: BoxShape.circle,
    );
  }

  //新的仪表盘
  Widget techMeter() {
    return Positioned(
      right: ScreenUtil().setWidth(467.0),
      top: ScreenUtil().setHeight(160.0),
      width: ScreenUtil().setWidth(400.0),
      height: ScreenUtil().setWidth(400),
      child: Container(
        decoration: _techMeterBackground(),
        child: _techMeterPointer(),
      ),
    );
  }

  Transform _techMeterPointer() {
    double pointerMargin = ScreenUtil().setWidth(160.0);
    return Transform.rotate(
      angle: _meterAngle,
      origin: Offset(ScreenUtil().setWidth(0.0), ScreenUtil().setWidth(0.0)),
      child: Container(
        margin: EdgeInsets.only(
            left: pointerMargin,
            right: pointerMargin,
            top: ScreenUtil().setWidth(1.0),
            bottom: ScreenUtil().setWidth(80.0)),
        child: Image.asset(
          'assets/meter_pointer.png',
        ),
      ),
    );
  }

  //指示表
  Widget rightMeter({MeterChange? valueChange}) {
    return Positioned(
      right: ScreenUtil().setWidth(520.0),
      top: ScreenUtil().setHeight(130.0),
      width: ScreenUtil().setWidth(100.0),
      height: ScreenUtil().setWidth(113),
      child: meter(valueChange),
    );
  }

  //指示表
  Widget leftMeter({MeterChange? valueChange}) {
    return Positioned(
      left: ScreenUtil().setWidth(520.0),
      top: ScreenUtil().setHeight(130.0),
      width: ScreenUtil().setWidth(100.0),
      height: ScreenUtil().setWidth(113),
      child: meter(valueChange),
    );
  }

  Widget meter(MeterChange? valueChange) {
    return Column(
      children: <Widget>[
        Expanded(
          child: AspectRatio(
            aspectRatio: 155 / 134,
            child: Container(
              width: ScreenUtil().setWidth(100.0),
              alignment: const Alignment(0, 0),
              decoration: const BoxDecoration(
                image: DecorationImage(
                  image: AssetImage('assets/speed_icon.png'),
                  fit: BoxFit.fill,
                ),
                //color: Colors.black26,
              ),
              child: Text(
                (valueChange != null ? valueChange() : 0).toString(),
                style: Theme.of(context)
                    .textTheme
                    .bodyText1
                    ?.apply(color: Colors.white),
              ),
            ),
          ),
        ),
        Container(
          child: Center(
            child: Text(
              'r/min',
              style: Theme.of(context)
                  .textTheme
                  .bodyText1
                  ?.apply(color: Colors.white),
            ),
          ),
        ),
      ],
    );
  }

  // x(-1,1) y(-1,1)
  void setVertical({required double x, required double y}) {
    //bluetoothDanbao.setAction(speed: y);
    YundongjiaBle.instance.sendAdvertiseCommand(
        DeviceDataContext.instance.devcie.getSpeed(((1 - y) * 0x80).toInt()));
    if (needConvertMeter()) {
      setState(() {
        if (y < 0) {
          _meterAngle = (-2 * y - 1) * pi * 3 / 4;
        } else {
          _meterAngle = (2 * y - 1) * pi * 3 / 4;
        }
      });
    }
  }

  void setHorizontal({required double x, required double y}) {
    //bluetoothDanbao.setAction(direction: x);
    YundongjiaBle.instance.sendAdvertiseCommand(DeviceDataContext
        .instance.devcie
        .getDirection(((1 + x) * 0x80).toInt()));
  }

  @override
  Widget build(BuildContext context) {
    return Container(
        //child: RemotePage(),
        );
  }

  //路径按钮事件处理
  void pathBtnOntap() {
    // print('remoteBtnOntap 打开路径');
    if (functionType == FunctionType.Draw) {
      return;
    }
    // pushPage(context, PathPage());
  }

  //语音按钮事件处理
  void voiceBtnOntap() {
    // print('remoteBtnOntap 打开语音');
    if (functionType == FunctionType.Voice) {
      return;
    }
    // pushPage(context, VoicePage());
  }

  //遥控按钮事件处理
  void remoteBtnOntap() {
    // print('remoteBtnOntap 打开遥控');
    if (functionType == FunctionType.Remote) {
      return;
    }

    final deviceType = AppConfig.instance.deviceType;
    FunctionPage functionPage;
    // if (deviceType == DeviceType.Serial2_0) {
    //   functionPage = RemotePage20();
    // } else if (deviceType == DeviceType.Serial2_1) {
    //   functionPage = RemotePage21();
    // } else if (deviceType == DeviceType.Serial3_0) {
    //   functionPage = RemotePage30();
    // } else if (deviceType == DeviceType.Serial4_0) {
    //   functionPage = RemotePage40();
    // }

    // pushPage(context, functionPage ?? RemotePage40());
  }

  //陀螺仪按钮事件处理
  void gravityBtnOntap() {
    debugPrint('remoteBtnOntap 打开陀螺仪');
    if (functionType == FunctionType.Gravity) {
      return;
    }
    // pushPage(context, GravityPage());
  }

  void pushPage(BuildContext context, FunctionPage page) {
    Navigator.of(context).pushReplacement(
      PageRouteBuilder(
        transitionDuration: const Duration(milliseconds: 100),
        pageBuilder: (BuildContext context, Animation<double> animation,
            Animation secondaryAnimation) {
          return FadeTransition(
            //使用渐隐渐入过渡,
            opacity: animation,
            child: page, //路由B
          );
        },
      ),
    );
  }

  //设置按钮事件处理
  void onSettingTap() {}

  // 切换设置事件处理
  void onSwitchTap() {}

  //同时 停止
  void setBoth({required double speed, required double direction}) {
    // final bool force =
    //     ((speed - 0.0).abs() < 0.001) || ((direction - 0.0).abs() < 0.001);
    List<int> data = DeviceDataContext.instance.devcie.getStopPair();
    YundongjiaBle.instance.sendAdvertiseCommand(data);
  }

  void setData(int index, int value) {
    List<int> data = DeviceDataContext.instance.devcie.getDataAt(index, value);
    YundongjiaBle.instance.sendAdvertiseCommand(data);
  }

  Widget channelBtn(
      {required double right,
      required double top,
      required double width,
      required double height,
      required String imagename,
      GestureTapCallback? ontap}) {
    return Positioned(
      right: right,
      top: top,
      width: width,
      height: height,
      child: Container(
        decoration: BoxDecoration(
          image: DecorationImage(
            image: AssetImage(imagename),
          ),
        ),
        child: GestureDetector(
          onTap: ontap,
        ),
      ),
    );
  }
}
